package com.fc.remoting.core;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class RemotingThreadPool {
	private static RemotingThreadPool threadPool = null;

	public static final int KEEP_ALIVE_TIME = 60;
	private static final int QUEUE_SIZE = 500;

	private static ThreadPoolExecutor poolExecutor = null;

	private static AtomicLong tId = new AtomicLong(1);

	private RemotingThreadPool() {
		if (poolExecutor == null) {
			int processerNumber = Runtime.getRuntime().availableProcessors();
			int maxSize = processerNumber + 1;
			poolExecutor = new ThreadPoolExecutor(processerNumber, maxSize, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
					new LinkedBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadFactory() {

						@Override
						public Thread newThread(Runnable r) {
							Thread thread = new Thread(r, "RThread_" + tId.getAndIncrement());
							thread.setDaemon(false);
							return thread;
						}
					});
		}
	}

	public static class Instance {
		public static RemotingThreadPool getInstance() {
			if (threadPool == null) {
				threadPool = new RemotingThreadPool();
			}
			return threadPool;
		}
	}

	public void submitTask(Runnable task) {
		poolExecutor.submit(task);
	}
}
